/**
 * 项目名称（软件名称）：忠旺机械物资管理系统(mms)
 * 研发设计单位：忠旺机械设备制造有限公司机械设计院智能控制设计科设计与研发。
 * 版权所有：忠旺机械设备制造有限公司
 * 注：本项目的一切技术专利，使用规范归解释权由忠旺机械设备制造有限公司所有。
 * 软件版本：Ver 1.0.0
 * 文件路径：com.zhongwang.mms.module.purchase.service
 * 创建时间：2020年03月16日 14时06分
 **/
package com.zhongwang.mms.module.purchase.service;

import com.zhongwang.mms.base.BaseService;
import com.zhongwang.mms.common.JsonResult;
import com.zhongwang.mms.gen.entity.*;
import com.zhongwang.mms.module.basic.dao.TCostDao;
import com.zhongwang.mms.module.basic.dao.TWarehouseInfoDao;
import com.zhongwang.mms.module.purchase.constant.PurchaseConstant;
import com.zhongwang.mms.module.purchase.dao.*;
import com.zhongwang.mms.module.purchase.model.AllocationResaultModel;
import com.zhongwang.mms.module.purchase.model.PChangeOrderModel;
import com.zhongwang.mms.module.purchase.model.PInventoryModel;
import com.zhongwang.mms.module.purchase.model.POutOrder;
import com.zhongwang.mms.module.system.log.LogService;
import com.zhongwang.mms.util.ShiroUtils;
import com.zhongwang.mms.util.StringUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.CannotAcquireLockException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionSystemException;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName： PurWarInManageService
 * @Description： 入库单业务逻辑层
 * @Author： 徐一贺
 * @Date： 2020/3/16 14:06
 * @Version： V1.0
 **/

@Log4j2
@Service
public class PurWarOutManageService extends BaseService {
    @Autowired
    private PurWarInManageDao purWarInManageDao;
    @Autowired
    private TWarehouseInfoDao tWarehouseInfoDao;
    @Autowired
    private PurPOrderDetailDao purPOrderDetailDao;
    @Autowired
    private PurPOrderDao purPOrderDao;
    @Autowired
    private PurPInventoryDao purPInventoryDao;
    @Autowired
    private LogService logService;
    @Autowired
    private PurTDeptDao purTDeptDao;
    @Autowired
    private PurSystemDao purSystemDao;
    @Autowired
    private PurChangeDao purChangeDao;
    @Autowired
    private TCostDao tCostDao;

    /**
     * @FunctionName: findLastPRKOrderCode
     * @Description: 获取入库编码数量
     * @Author: 徐一贺
     * @CreateDate: 2020/3/17 14:17
     * @Phone: 18241927380
     * @Param:
     * @Return:
     * @Version:
     */
    public String findLastPRKOrderCode() {
        if (purWarInManageDao.findPRKOrderCodeCount() == 0) {
            return "";
        }
        return purWarInManageDao.findLastPRKOrderCode();
    }

    /**
     * @FunctionName: findLastPCKOrderCode
     * @Description: 获取最后出库的编码
     * @Author: 徐一贺
     * @CreateDate: 2020/3/17 14:17
     * @Phone: 18241927380
     * @Param:
     * @Return:
     * @Version:
     */
    public String findLastPCKOrderCode() {
        return purWarInManageDao.findLastPCKOrderCode();
    }

    /**
     * @param orderCodeType
     * @FunctionName: getOrderCode
     * @Description: 获取最新的单据编码
     * @Author: 徐一贺
     * @CreateDate: 2020/3/23 7:55
     * @Phone: 18241927380
     * @Param: orderCodeType 单据编码类型 PRK是入库 PCK是出库
     * @Return: String 返回最新的编码
     * @Version: 1.0.0
     */
    public String getOrderCode(int orderCodeType) {
        String orderCode = "";
        if (orderCodeType == PurchaseConstant.PRK) {
            orderCode = generatePRKOrderCode();
        } else if (orderCodeType == PurchaseConstant.PCK) {
            orderCode = generatePCKOrderCode();
        }
        return orderCode;
    }

    /**
     * @FunctionName: findLastPRKOrderCode
     * @Description: 获取最新出库单编码
     * @设计思路： 1.判断年后两位+月+日与当前年月日是否相同，如果相同且流水号则在流水号上递增1。
     * 2.如果数据为空则按照以PRK+年（后两位）月日+001生成外购件出库单编码。
     * 3.如果不相同则按照以PRK+年（后两位）月日+001生成外购件出库单编码。
     * @Author: 徐一贺
     * @CreateDate: 2020/3/17 14:22
     * @Phone: 18241927380
     * @Param:
     * @Return: String 最新出库单编码
     * @Version:
     */
    private String generatePRKOrderCode() {
        String newGeneratePRKOrderCode = "";
        //获取最后编码
        String lastPRKOrderCode = findLastPRKOrderCode();
        //获取当前时间简码
        String datetimeCode = new SimpleDateFormat("yyMMdd").format(new Date());
        Integer sn = 0;
        if (lastPRKOrderCode.length() > 0) {
            //获取外购件库最新最后的入库单号
            sn = Integer.parseInt(lastPRKOrderCode.substring(9));
        }
        if (lastPRKOrderCode.length() == 0) {
            newGeneratePRKOrderCode = "PRK" + new SimpleDateFormat("yyMMdd").format(new Date()) + "001";
        } else if (!lastPRKOrderCode.substring(3, 9).equals(datetimeCode)) {
            newGeneratePRKOrderCode = "PRK" + new SimpleDateFormat("yyMMdd").format(new Date()) + "001";
        } else {
            newGeneratePRKOrderCode = "PRK" + new SimpleDateFormat("yyMMdd").format(new Date()) + String.format("%03d", (sn + 1));
        }
        return newGeneratePRKOrderCode;
    }

    /**
     * @FunctionName: findLastPRKOrderCode
     * @Description: 获取最新出库单编码
     * @设计思路： 1.判断年后两位+月+日与当前年月日是否相同，如果相同且流水号则在流水号上递增1。
     * 2.如果数据为空则按照以PRK+年（后两位）月日+001生成外购件出库单编码。
     * 3.如果不相同则按照以PRK+年（后两位）月日+001生成外购件出库单编码。
     * @Author: 徐一贺
     * @CreateDate: 2020/3/17 14:22
     * @Phone: 18241927380
     * @Param:
     * @Return: String 最新出库单编码
     * @Version:
     */
    private String generatePCKOrderCode() {
        String newGeneratePRKOrderCode = "";
        //获取最后编码
        String lastPCKOrderCode = findLastPCKOrderCode();
        //获取当前时间简码
        String datetimeCode = new SimpleDateFormat("yyMMdd").format(new Date());
        if (lastPCKOrderCode == null) {
            newGeneratePRKOrderCode = "PCK" + new SimpleDateFormat("yyMMdd").format(new Date()) + "001";
        } else if (!lastPCKOrderCode.substring(3, 9).equals(datetimeCode)) {
            newGeneratePRKOrderCode = "PCK" + new SimpleDateFormat("yyMMdd").format(new Date()) + "001";
        } else {
            //获取外购件库最新最后的入库单号
            Integer sn = Integer.parseInt(lastPCKOrderCode.substring(9));
            newGeneratePRKOrderCode = "PCK" + new SimpleDateFormat("yyMMdd").format(new Date()) + String.format("%03d", (sn + 1)); //25为int型 ;
        }
        return newGeneratePRKOrderCode;
    }
//    /**
//     * @FunctionName: create
//     * @Description: 创建入库单
//     * @Author: 徐一贺
//     * @CreateDate: 2020/3/23 10:46
//     * @Phone: 18241927380
//     * @Param: [pInOrder] 入库数据
//     * @Return: com.zhongwang.mms.common.JsonResult 返回结果
//     * @Version: 1.0.0
//     */
//    public JsonResult create(PInOrder pInOrder) {
//        //验证
//        JsonResult jsonResult = new JsonResult();
//        List<String> result = new ArrayList<>();
//        for (int i = 0; i < pInOrder.getInsertData().size(); i++) {
//            if (pInOrder.getInsertData().get(i).getOdaMatCode() == null || pInOrder.getInsertData().get(i).getOdaMatCode() == "") {
//                result.add("\n第" + (i + 1) + "行" + " 物料编码 为空");
//            }
//            if (pInOrder.getInsertData().get(i).getOdaMatDesc() == null || pInOrder.getInsertData().get(i).getOdaMatDesc() == "") {
//                result.add("\n第" + (i + 1) + "行" + " 物料描述 为空");
//            }
//            if (pInOrder.getInsertData().get(i).getOdaNum() == null || pInOrder.getInsertData().get(i).getOdaNum() == 0) {
//                result.add("\n第" + (i + 1) + "行" + " 数量为空 为空");
//            }
//            if (pInOrder.getInsertData().get(i).getOdaNumUnit() == null || pInOrder.getInsertData().get(i).getOdaNumUnit() == "") {
//                result.add("\n第" + (i + 1) + "行" + " 单位为空 为空");
//            }
//            if (pInOrder.getInsertData().get(i).getOdaTotalPrice() == null || pInOrder.getInsertData().get(i).getOdaTotalPrice() <= 0) {
//                result.add("\n第" + (i + 1) + "行" + " 金额为空 为空");
//            }
//            if (pInOrder.getInsertData().get(i).getOdaNumPrice() == null || pInOrder.getInsertData().get(i).getOdaNumPrice() <= 0) {
//                result.add("\n第" + (i + 1) + "行" + " 单价为空 为空");
//            }
//            if (pInOrder.getInsertData().get(i).getOdaTrackCode() == null || pInOrder.getInsertData().get(i).getOdaTrackCode() == "") {
//                result.add("\n第" + (i + 1) + "行" + " 跟踪号为空 为空");
//            }
//            if (pInOrder.getInsertData().get(i).getOdaProName() == null || pInOrder.getInsertData().get(i).getOdaProName() == "") {
//                result.add("\n第" + (i + 1) + "行" + " 项目文本为空 为空");
//            }
//            if (pInOrder.getInsertData().get(i).getOdaProCode() == null || pInOrder.getInsertData().get(i).getOdaProCode() == "") {
//                result.add("\n第" + (i + 1) + "行" + " 项目编码为空 为空");
//            }if (StringUtils.isContainChinese(pInOrder.getInsertData().get(i).getOdaProCode())) {
//                result.add("\n第" + (i + 1) + "行" + " 项目编码不可出现汉字 违规字符");
//            }
//            if (pInOrder.getInsertData().get(i).getWarehouseLocation() == null || pInOrder.getInsertData().get(i).getWarehouseLocation() == "") {
//                result.add("\n第" + (i + 1) + "行" + " 库存地为空 为空");
//            }
//            if (pInOrder.getInsertData().get(i).getOdaPosition() == null || pInOrder.getInsertData().get(i).getOdaPosition() == "") {
//                result.add("\n第" + (i + 1) + "行" + " 仓位为空 为空");
//            }
//        }
//        // 原料基础信息不存在，提示不存在原料信息，跳出方法，待补完原料基础信息后 重新保存
//        if (result.size() > 0) {
//            result.add("\n单据保存失败，请先维护以上原料信息！");
//            jsonResult.setData(result);
//            return jsonResult;
//        }
//
//        //创建主单数据
//        POrder pOrder = new POrder();
//        pOrder.setOdrCode(pInOrder.getFormData().getOdrCode());
//        pOrder.setOdrRemark(pInOrder.getFormData().getOdrRemark());
//        pOrder.setOdrType(1);
//        pOrder.setOdrRedFlag(0);
//        pOrder.setOdrDate(new Date());
//        pOrder.setOdrTakePerson(ShiroUtils.getUser().getName());
//        pOrder.setOdrReqFlag(0);
//        pOrder.setOdrPlaaFlag(0);
//        pOrder.setOdrMakeDate(new Date());
//        Integer odrId = purPOrderDao.insert(pOrder);
//        try {
//            //创建明细单
//            for (com.zhongwang.mms.module.purchase.model.POrderDetail pOrderDetailModel : pInOrder.getInsertData()) {
//                POrderDetail pOrderDetail = new POrderDetail();
//                pOrderDetail.setOdaOdrId(odrId);
//                pOrderDetail.setOdaMatCode(pOrderDetailModel.getOdaMatCode());
//                pOrderDetail.setOdaMatDesc(pOrderDetailModel.getOdaMatDesc());
//                pOrderDetail.setOdaNum(pOrderDetailModel.getOdaNum());
//                pOrderDetail.setOdaNumUnit(pOrderDetailModel.getOdaNumUnit());
//                pOrderDetail.setOdaTotalPrice(pOrderDetailModel.getOdaTotalPrice());
//                pOrderDetail.setOdaNumPrice(pOrderDetailModel.getOdaNumPrice());
//                pOrderDetail.setOdaTrackCode(pOrderDetailModel.getOdaTrackCode());
//                pOrderDetail.setOdaProName(pOrderDetailModel.getOdaProName());
//                pOrderDetail.setOdaProCode(pOrderDetailModel.getOdaProCode());
//                pOrderDetail.setOdaWhiId(tWarehouseInfoDao.findWarehouseInfoByCode(pOrderDetailModel.getWarehouseLocation()).getWhiId());
//                pOrderDetail.setOdaPosition(pOrderDetailModel.getOdaPosition());
//                if (pOrderDetailModel.getOdaBookkeepingDate() != null) {
//                    pOrderDetail.setOdaBookkeepingDate(new SimpleDateFormat("yyyy-MM-dd").parse(pOrderDetailModel.getOdaBookkeepingDate().replace('.','-')));
//                }
//                pOrderDetail.setOdaRemark(pOrderDetailModel.getOdaRemark());
//                //检测库存表中是否有相同的数据
//                PInventory pInventory = new PInventory();
//                pInventory.setItyMatCode(pOrderDetail.getOdaMatCode());
//                pInventory.setItyMatDesc(pOrderDetail.getOdaMatDesc());
//                pInventory.setItyNum(pOrderDetail.getOdaNum());
//                pInventory.setItyNumUnit(pOrderDetail.getOdaNumUnit());
//                pInventory.setItyAvaNum(pOrderDetail.getOdaNum());
//                pInventory.setItyAmount(pOrderDetail.getOdaTotalPrice());
//                pInventory.setItyPrice(pOrderDetail.getOdaNumPrice());
//                pInventory.setItyTrackCode(pOrderDetail.getOdaTrackCode());
//                pInventory.setItyProName(pOrderDetail.getOdaProName());
//                pInventory.setItyProCode(pOrderDetail.getOdaProCode());
//                pInventory.setItyWhiId(pOrderDetail.getOdaWhiId());
//                pInventory.setItyPosition(pOrderDetail.getOdaPosition());
//                pInventory.setItyDataStatus(0);
//                pInventory.setItyRowNo(purPOrderDetailDao.insert(pOrderDetail));
//                //如果检测结果为0则侧入数据，否则合并数据
//                //物料编码+行号（入库明细id）+项目文本+项目编码+库存地为批次字段，批次字段相同时，入库时要做物料合并，数量相加，
//                PInventory pInventoryObj = purPInventoryDao.findInventoryByParam(pInventory);
//               //如果库存表没有此数据
//                if (null == pInventoryObj) {
//                    //往库存表插入数据
//                    purPInventoryDao.insertSelective(pInventory);
//                } else {
//                    ///如果库存表有此数据，开始进行合并数据：合并改规则如下
//                    //单价=总金额之和/总数量，
//                    Double price = (pInventory.getItyAmount() + pInventoryObj.getItyAmount()) / (pInventory.getItyNum() + pInventoryObj.getItyNum());
//                    //总金额=计算后的单价*数量,有数据库自动计算
//                    //总数量
//                    Double totalNum = pInventory.getItyNum() + pInventoryObj.getItyNum();
//                    //单价
//                    pInventoryObj.setItyPrice(price);
//                    //总数量
//                    pInventoryObj.setItyNum(totalNum);
//                    purPInventoryDao.updateByPrimaryKeySelective(pInventoryObj);
//                }
//            }
//            result.add("单据保存成功！");
//            jsonResult.setData(result);
//            //记录操作日志
//            logService.saveLog("出入库操作-入库", "入库单据编码：" + pOrder.getOdrCode());
//        } catch (Exception ex) {
//            //记录异常错误日志信息
//            log.error("【正式入库-异常日志】:异常入库单编码："+pOrder.getOdrCode()+"{" + ex.getMessage() + "}");
//            result.add("单据保存失败！");
//            jsonResult.setData(result);
//        }
//        return jsonResult;
//    }

    /**
     * @FunctionName: findDeptList
     * @Description: 获取部门列表
     * @Author: 徐一贺
     * @CreateDate: 2020-3-24 13:35:14
     * @Phone: 18241927380
     * @Param: []
     * @Return: com.zhongwang.mms.common.JsonResult
     * @Version: 1.0.0
     */
    public List<TDept> findDeptList() {
        TDept tDept = new TDept();
        tDept.setDepPid(9);
        TDeptExample tDeptExample = new TDeptExample();
        tDeptExample.or().andDepNameNotEqualTo("外厂").andDepStatusEqualTo(1);
        return purTDeptDao.selectByExample(tDeptExample);
    }

    /**
     * @FunctionName: findInventoryList
     * @Description: 根据条件查询库存信息
     * @Author: 徐一贺
     * @CreateDate: 2020/3/24 16:50
     * @Phone: 18241927380
     * @Param: param 查询参数
     * @Return: List<PInventory> 库存信息
     * @Version: 1.0.0
     */
    public List<PInventoryModel> findInventoryList(PInventoryModel param) {
        param.setSort(StringUtils.convertFieldToColumn(param.getSort()));
        //return purPInventoryDao.findInventoryList(param);
        return purPInventoryDao.findInventoryListByOut(param);
    }

    /**
     * @FunctionName: getCurrentDate
     * @Description: 获取数据库服务器当前日期
     * @Author: 徐一贺
     * @CreateDate: 2020/3/26 15:37
     * @Phone: 18241927380
     * @Return: String 数据库服务器当前日期
     * @Version: 1.0.0
     */
    public String getCurrentDate() {
        return purSystemDao.getCurrentDate();
    }

    /**
     * @FunctionName: findInventoryListByIds
     * @Description: 请填写方法描述
     * @Author: 徐一贺
     * @CreateDate: 2020/3/26 16:27
     * @Phone: 18241927380
     * @Param: ityIds
     * @Return: List<POrderDetail>
     * @Version: 1.0.0
     */
    public List<PInventoryModel> findInventoryListByIds(String ityIds) {
        return purPInventoryDao.findInventoryListByIds(ityIds);
    }

    /**
     * @FunctionName: createRequestMaterial
     * @Description: 领料出库
     * @DesignIdea: 新增智能分析串料信息，生成打印串料形式单据
     * @Author: 徐一贺
     * @CreateDate: 2020/6/23 9:47
     * @Phone: 18241927380
     * @Param:
     * @Return:
     * @Throw:
     * @Version: v 3.5.1
     */
    @Transactional(rollbackFor = Exception.class)
    public AllocationResaultModel createRequestMaterial(POutOrder pOutOrder,String code,AllocationResaultModel allocationResaultModelPara) throws Exception {
        AllocationResaultModel allocationResaultModel =allocationResaultModelPara;
        //创建主单数据
        POrder pOrder = new POrder();
        pOrder.setOdrCode(code);
        pOrder.setOdrRemark(pOutOrder.getFormData().getOdrRemark());
        pOrder.setOdrTakePerson(pOutOrder.getFormData().getOdrTakePerson());
        pOrder.setOdrMakePersonId(ShiroUtils.getUser().getId());
        pOrder.setOdrChangeFlag(0);
        pOrder.setOdrType(2);
        pOrder.setOdrRedFlag(0);
        pOrder.setOdrDate(pOutOrder.getFormData().getOdrDate());
        pOrder.setOdrReqFlag(0);
        pOrder.setOdrMakeDate(new Date());
        pOrder.setOdrTakeWorkshopId(pOutOrder.getFormData().getOdrTakeWorkshopId());
        pOrder.setOdrOutType(2);
        purPOrderDao.insert(pOrder);
        Integer odrId = pOrder.getOdrId();
        //创建明细单
        for (com.zhongwang.mms.module.purchase.model.POrderDetail pOrderDetailModel : pOutOrder.getInsertData()) {
            PInventory pInventory = purPInventoryDao.findByPrimaryKey(pOrderDetailModel.getItyId());
            if (pInventory.getItyChangeFlag() != null && pInventory.getItyChangeFlag() != 2) {
                allocationResaultModel.setIsChangeFlag(1);
                //1.溯源：找回此物料最原始的串料信息，即始祖库存信息，找寻方式，
                //通过此库存ID在串料执后的信息中获取上一级，以此类推。
                PInventoryModel pInventoryModel = findAncestorChangeData(pInventory.getItyId());
                //2.累计计算剩余库存量：通过始祖信息获取子孙的在库数量与本身的在库数量之和就是真实在库数量之和
                //pOrderDetailModel.setOdaNumSource(pInventoryModel.getItyNum() + getChangeOrderInvCount(pInventoryModel.getItyId()));
                PInventory getNumModel = new PInventory();
                getNumModel.setItyNum(pInventoryModel.getItyNum());
                getNumModel.setItyId(pInventoryModel.getItyId());
                pOrderDetailModel.setOdaNumSource(getChangePInventoryAllNum(getNumModel));
                pOrderDetailModel.setOdaProCodeSource(pInventoryModel.getItyProCode());
                pOrderDetailModel.setOdaProNameSource(pInventoryModel.getItyProName());
                //3.更改串料状态为串料出库状态
                PChangeOrderModel pChangeOrderModel = purChangeDao.getChangeCountByCeoNeedItyId(pOrderDetailModel.getItyId());
                if (pChangeOrderModel != null) {
                    //4.2020年7月15日午休后：盖世奇说：.所串料都被出库完毕才能算串料，否则一直是执行
                    PInventory changePInv = purPInventoryDao.getPInventoryByPK(pChangeOrderModel.getCeoNeedItyId());
                    if (changePInv.getItyNum().equals(pOrderDetailModel.getOdaNum()) && pChangeOrderModel.getCeoAppyStatus().equals(3)) {
                        pChangeOrderModel.setCeoAppyStatus(5);
                        purChangeDao.updatePChangeOrderCeoAppyStatusByPk(pChangeOrderModel);
                    }
                }
            }
            POrderDetail pOrderDetail = new POrderDetail();
            pOrderDetail.setOdaType(2);
            pOrderDetail.setOdaOdrId(odrId);
            pOrderDetail.setOdaRedFlag(0);
            pOrderDetail.setOdaMatCode(pOrderDetailModel.getOdaMatCode());
            pOrderDetail.setOdaSapCode(pOrderDetailModel.getOdaSapCode());
            pOrderDetail.setOdaMatDesc(pOrderDetailModel.getOdaMatDesc());
            pOrderDetail.setOdaNum(pOrderDetailModel.getOdaNum());
            pOrderDetail.setOdaNumUnit(pOrderDetailModel.getOdaNumUnit());
            pOrderDetail.setOdaTotalPrice(pInventory.getItyPrice() * pOrderDetailModel.getOdaNum());
            pOrderDetail.setOdaNumPrice(pInventory.getItyPrice());
            pOrderDetail.setOdaTrackCode(pOrderDetailModel.getOdaTrackCode());
            pOrderDetail.setOdaProName(pOrderDetailModel.getOdaProName());
            pOrderDetail.setOdaProCode(pOrderDetailModel.getOdaProCode());
            pOrderDetail.setOdaPosition(pOrderDetailModel.getOdaPosition());
            pOrderDetail.setOdaTakeType(pOrderDetailModel.getOdaTakeType());
            if (pOrderDetailModel.getOdaBookkeepingDate() != null) {
                pOrderDetail.setOdaBookkeepingDate(new SimpleDateFormat("yyyy-MM-dd").parse(pOrderDetailModel.getOdaBookkeepingDate().replace('.', '-')));
            }
            pOrderDetail.setOdaSpec(pOrderDetailModel.getOdaSpec());
            pOrderDetail.setOdaOutItyId(pOrderDetailModel.getItyId());
            PInventoryModel pInventoryModel = findAncestorChangeData(pInventory.getItyId());
            pOrderDetail.setOdaAtThatTimeAncestorsNum(pOrderDetailModel.getOdaNumSource());
            pOrderDetail.setOdaAtThatTimeAncestorsProCode(pInventoryModel.getItyProCode());
            pOrderDetail.setOdaAtThatTimeAncestorsTrackCode(pInventoryModel.getItyTrackCode());
            pOrderDetail.setOdaOutWhiId(pInventoryModel.getOdaWhiId());
            pOrderDetail.setOdaStockType(pInventory.getItyStockType());
            pOrderDetail.setOdaRemarkType(pOrderDetailModel.getOdaRemarkType());
            pOrderDetail.setContractNo(pOrderDetailModel.getContractNo());
            pOrderDetail.setOdaCaseNo(pOrderDetailModel.getOdaCaseNo());
            pOrderDetail.setOdaWhiId(pInventory.getItyWhiId());
            pOrderDetail.setOdaOutWhiId(pInventory.getItyWhiId());
            pOrderDetail.setOdaBrand(pInventory.getItyBrand());
            purPOrderDetailDao.insertPOrderDetail(pOrderDetail);
            Thread.sleep(3000);
            PInventory changeNum = new PInventory();
            changeNum.setItyId(pOrderDetailModel.getItyId());
            changeNum.setItyNum(pInventory.getItyNum() - pOrderDetailModel.getOdaNum());
            Double avaNum = pInventory.getItyAvaNum() - pOrderDetailModel.getOdaNum();
            if (avaNum < 0) {
                avaNum = 0d;
            }
            changeNum.setItyAvaNum(avaNum);
            if (changeNum.getItyNum() < 0 || changeNum.getItyAvaNum() < 0) {
                Exception exception = new Exception();
                throw exception;
            }
            if (purPInventoryDao.updatePInventoryNumPrimaryKey(changeNum) == 0) {
                Exception exception = new Exception();
                throw exception;
            }
        }
        allocationResaultModel.setMessage("单据保存成功！");
        return allocationResaultModel;
    }

    /**
     * @FunctionName: findAncestorChangeData
     * @Description: 根据子孙ID 获取串料历史中始祖的信息，并获取始祖信息时的库存数量
     * @DesignIdea: 使用递归获取始祖库存ID，并返回当前信息的始祖库存信息
     * @Author: 徐一贺
     * @CreateDate: 2020/6/29 9:47
     * @Phone: 18241927380
     * @Param: [ceoNeedItyId] 需求库存ID
     * @Return: [PInventoryModel]检索到的库存信息
     * @Throw:
     * @Version: v 1.0.0
     */
    public PInventoryModel findAncestorChangeData(Integer ceoNeedItyId) {
        PInventoryModel result = purPInventoryDao.getInventoryByPrimaryKey(ceoNeedItyId);
        PChangeOrderModel currentModel = new PChangeOrderModel();
        currentModel.setCeoNeedItyId(ceoNeedItyId);
        while (true) {
            if (currentModel != null) {
                currentModel = purChangeDao.getChangeCountByCeoNeedItyId(currentModel.getCeoNeedItyId());
            }
            if (currentModel != null) {
                result = purPInventoryDao.getInventoryByPrimaryKey(currentModel.getCeoUseItyId());
                currentModel = purChangeDao.getChangeCountByCeoNeedItyId(currentModel.getCeoUseItyId());
            } else {
                break;
            }
        }
        return result;
    }

    /**
     * 过去数量之和
     * 如果是成本中心的加上串料数量
     *
     * @return
     */
    public Double getChangePInventoryAllNum(PInventory pInventory) {
        List<PChangeOrder> useChangeOrderList = purChangeDao.findPChangeOrderListByCeoUseItyIdAndCeoApplyStatus(pInventory.getItyId());
        if (useChangeOrderList.size() > 0) {
            for (PChangeOrder pChangeOrder : useChangeOrderList) {
                PInventory child = purChangeDao.getInventoryPrimaryKey(pChangeOrder.getCeoNeedItyId());
                if (child.getItyStockType().equals(2) || tCostDao.getTCostByCosProCode(child.getItyProCode()) != null) {
                    pInventory.setItyNum(pInventory.getItyNum() + getChangePInventoryAllNum(child));
                } else {
                    pInventory.setItyNum(pInventory.getItyNum() + getChangePInventoryAllNum(child) - child.getItyNum());
                }
            }
        }
        return pInventory.getItyNum();
    }

    /**
     * @FunctionName: getChangeOrderInvCount
     * @Description: 获取已执行的和已出库库存信息，获取其数量进行相加
     * @DesignIdea: 默认认为只串一次料
     * @Author: 徐一贺
     * @CreateDate: 2020/6/29 13:32
     * @Phone: 18241927380
     * @Param:
     * @Return:
     * @Throw:
     * @Version: v 1.0.0
     */
    private Double getChangeOrderInvCount(Integer ceoUseItyId) {
        Double result = 0d;
        //获取根节点列表
        List<PChangeOrderModel> pChangeOrderModelList = purChangeDao.findPChangeOrderListByCeoUseItyId(ceoUseItyId);
        for (PChangeOrderModel pChangeOrderModel : pChangeOrderModelList) {
            PInventoryModel pInvModel = purPInventoryDao.getInventoryByPrimaryKey(pChangeOrderModel.getCeoNeedItyId());
            result += pInvModel.getItyNum();
        }
        return result;
    }

    /**
     * getPInventoryByPrimaryKey
     * 根据主键获取库存信息
     *
     * @param ityId
     * @return
     */
    public PInventory getPInventoryByPrimaryKey(Integer ityId) {
        return purPInventoryDao.getPInventoryByPK(ityId);
    }
}